<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\AdminNodeModel;

/**
 * 后台权限节点增删改查控制器
 */
class AdminNode extends Controller
{
    /**
     * 显示权限节点列表
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        //接受搜索条件
        $search = $request->input('search');

        if (empty($search)) {

            $where = [];

        } else {

            $where = [['desc', 'like', "%$search%"]];
        }

        $nodes = AdminNodeModel::select('id', 'name', 'desc')->where($where)->paginate(10);

        return view('Admin.adminUser.admin-permission', ['nodes' => $nodes, 'kw' => $search]);
    }

    /**
     * 显示添加权限节点的页面
     */
    public function create()
    {
        //
        return view('Admin.adminUser.admin-node-add');
    }

    /**
     * 处理添加节点
     */
    public function store(Request $request)
    {
        //
        $this->validate($request, [
        'name' => 'required',
        'desc' => 'required',
        ],[
            'name.required' => '节点名不能为空哦！',
            'desc.required' => '描述不可以为空哦！',
        ]);

        $data['name'] = $request->input('name');
        $data['desc'] = $request->input('desc');

        $res = AdminNodeModel::insert($data);

        if ( $res ) {

            return back()->with('message', '添加节点成功');

        } else {

            return back()->with('message', '添加节点失败');

        }

    }

    /**
     * 显示编辑权限节点页面
     */
    public function edit($id)
    {
        //
        $node = AdminNodeModel::find($id);

        return view('Admin.adminUser.admin-node-edit',['node' => $node]);

    }

    /**
     * 执行权限节点编辑
     */
    public function update(Request $request, $id)
    {
        //
        $this->validate($request, [
        'name' => 'required',
        'desc' => 'required',
        ],[
            'name.required' => '节点名不能为空哦！',
            'desc.required' => '描述不可以为空哦！',
        ]);

        $data['name'] = $request->input('name');
        $data['desc'] = $request->input('desc');

        $res = AdminNodeModel::where('id', $id)->update($data);

        if ($res) {

            return back()->with('message', '权限节点编辑成功');

        }

        return back()->with('message', '服务器繁忙，请稍后再试');

    }

    /**
     * 处理删除权限节点
     */
    public function destroy(Request $request)
    {

        $res = AdminNodeModel::where('id', $request->id )->delete();

        if ($res) {

            return response()->json($res);

        }

        return back()->with('message', '删除失败');
    }

}
